package com.holystone.orca.util;

import org.apache.log4j.Logger;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateDiffMonth {
	private static final Logger logger = Logger.getLogger(DateDiffMonth.class);
	
	public static void main(String[] argv) throws Exception {
		logger.debug(getMonthDiff("1900-11-01", "1901-01-21"));
	}

	/**
	 * 两个时间之间相差距离多少天
	 * 
	 * @param str1
	 *            时间参数 1：
	 * @param str2
	 *            时间参数 2：
	 * @return 相差天数
	 */
	public static long getDistanceDays(String str1, String str2)
			throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy/MM/dd");
		Date one;
		Date two;
		if (str1.contains("/")) {
			one = timeFormat.parse(str1);
		} else {
			one = df.parse(str1);
		}
		long days = 0;
		try {
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			// if(time1<time2) {
			// diff = time2 - time1;
			// } else {
			diff = time1 - time2;
			// }
			days = diff / (1000 * 60 * 60 * 24);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return days;
	}

	/**
	 * 得到两日期相差几个月
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static long getMonthDiff(String startDate, String endDate)
			throws Exception {
		long monthday;
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate1 = fmt.parse(startDate);

		Calendar starCal = Calendar.getInstance();
		starCal.setTime(startDate1);

		int sYear = starCal.get(Calendar.YEAR);
		int sMonth = starCal.get(Calendar.MONTH);
		int sDay = starCal.get(Calendar.DAY_OF_MONTH);

		Date endDate1 = fmt.parse(endDate);
		Calendar endCal = Calendar.getInstance();
		endCal.setTime(endDate1);
		int eYear = endCal.get(Calendar.YEAR);
		int eMonth = endCal.get(Calendar.MONTH);
		int eDay = endCal.get(Calendar.DAY_OF_MONTH);

		monthday = ((eYear - sYear) * 12 + (eMonth - sMonth));

		// 这里计算零头的情况，根据实际确定是否要加1 还是要减1
		if (sDay < eDay) {
			monthday = monthday + 1;
		}
		return monthday;
	}

}
